package com.augurit.gis.flex;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.augurit.gis.common.util.DateUtil;


public class BaseServlet extends HttpServlet{


	
	protected static final String CHAR_SET = "utf-8";
	
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		super.doPost(request, response);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	private WebApplicationContext ctx = null;
	protected Object getBean(String id) {
		 if(ctx == null){
			 ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		 }
         return ctx.getBean(id);
	 }
	
	protected void writeJson2Client(HttpServletResponse response,
			Object object) throws IOException {
		writeJson2Client(response, object, CHAR_SET);
	}
	protected void writeJson2Client(HttpServletResponse response,
			Object object,String charSet) throws IOException {
		if(object != null){
				String result = null;
				if(object instanceof Number || object instanceof String || object instanceof Boolean){
					result = object.toString();
				}else if(object instanceof Date){
					result = DateUtil.date2ChinaString((Date) object);
				}else if(object instanceof Collection || object.getClass().isArray()){
					 JsonConfig jsonConfig = new JsonConfig();   
				        jsonConfig.registerJsonValueProcessor(Date.class,  new JsonDateValueProcessor());   
					
				        result = JSONArray.fromObject(object,jsonConfig).toString();
				}else if(object instanceof BaseForm){
					result = JSONObject.fromObject(object).toString();
				}else if(object instanceof Object){
					result = JSONObject.fromObject(object).toString();
				}
				System.out.println(result);
				response.setCharacterEncoding(charSet);
				response.setContentType("text/json; charset="+charSet);
				response.getWriter().write(result);
		}
	}


}
